<template>
  <div class="add-news">
    <el-form ref="form" :rules="rules" :model="form" label-width="90px">
      <!-- 标题 -->
      <el-form-item label="文章标题:" prop="title">
        <el-input v-model.trim="form.title" />
      </el-form-item>
      <!-- 封面 -->
      <el-form-item label="文章封面:" prop="cover">
        <el-upload
          class="upload-demo"
          action="action"
          :show-file-list="false"
          :http-request="handleUpload"
          :before-upload="beforeUpload"
        >
          <img v-if="form.cover" :src="form.cover">
          <i v-else class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <!-- 内容 -->
      <el-form-item label="文章内容:" prop="content">
        <div class="rich-text" style="border: 1px solid #ccc;">
          <!-- 工具栏 -->
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :default-config="toolbarConfig"
          />
          <!-- 菜单栏 -->
          <Editor
            v-model="form.content"
            style="height: 500px; overflow-y: hidden;"
            :default-config="editorConfig"
            @onCreated="onCreated"
          />
        </div>
      </el-form-item>
      <div class="btn">
        <el-button type="primary" round @click="submitAdd('form')">提交</el-button>
        <el-button type="info" round @click="onCancel">返回</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { addNews, onUpdated, editNews, getNews } from '@/api/news'
export default {
  name: 'NewsMange',
  components: { Editor, Toolbar },
  props: {
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      form: {
        title: '',
        cover: '',
        content: ''
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        cover: [{ required: true, message: '请选择封面', trigger: 'blur' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      },
      formData: null,
      loading: false,
      editor: null,
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            server: 'http://localhost:3005/upload/news',
            customInsert(res, insertFn) {
              const url = res.data.imgUrl
              insertFn(url)
            },
            fieldName: 'files',
            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 1 * 1024 * 1024, // 1M
            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 1,
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['image/*'],
            // 超时时间，默认为 10 秒
            timeout: 15 * 1000, // 15 秒
            // 自定义增加 http  header
            headers: {
              Accept: 'text/x-json',
              Authorization: `Bearer ${getToken()}`
            }
          }
        }
      }
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  created() {
    if (this.type === 'edit') {
      this.getOneNews()
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    toolbarConfig() {

    },
    // 上传文件之前的钩子函数
    beforeUpload(file) {
      const type = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (type !== 'jpg' && type !== 'png' && type !== 'jpeg') {
        this.$message.error('只能上传jpg/png/jpeg文件')
        return false
      }
      if (file.size > 500 * 1024) {
        this.$message.error('文件大小不能超过500kb')
        return false
      }
      const formData = new FormData()
      formData.append('files', file)
      this.formData = formData
    },
    // 上传图片成功的回调函数
    async handleUpload() {
      const formData = this.formData
      try {
        const res = await onUpdated(formData)
        this.form.cover = res.data.imgUrl
        this.$message.success('图片上传成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取单条新闻数据
    async getOneNews() {
      try {
        const Id = this.id
        var { data: { title, cover, content }} = await getNews(Id)
        this.form = { title, cover, content }
      } catch (error) {
        console.log(error)
      }
    },
    // 提交
    submitAdd(formName) {
      this.$refs[formName].validate(async(valid) => {
        const form = this.form
        if (valid) {
          try {
            this.loading = true
            this.id ? await editNews(this.id, form) : await addNews(form)
            this.$message.success(this.id ? '修改成功' : '添加成功')
            this.loading = false
            this.$router.replace('/news/index')
          } catch (error) {
            console.log(error)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 返回
    onCancel() {
      this.form = {
        title: '',
        cover: '',
        content: ''
      }
      this.$router.replace('/news/index')
    }
  }
}
</script>

<style lang="scss" scoped>
.add-news {
  margin: 20px 20px 0 50px;
}
.rich-text {
  margin-top: 10px;
}
.btn {
  padding: 20px 0 50px 90px;
}
</style>
